package com.cgbl.cg.vm.home

import android.app.Application
import androidx.databinding.ObservableField
import api.UserServiceFactory
import com.robot.base.base.vm.GLBaseViewModel
import com.robot.base.common.api.AbstractViewModelSubscriber
import com.robot.base.model.PageListBean
import com.robot.base.model.PreferentPageBean
import com.robot.base.model.ResourceBean
import me.goldze.mvvmhabit.binding.command.BindingAction
import me.goldze.mvvmhabit.binding.command.BindingCommand
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent
import me.goldze.mvvmhabit.http.BaseResponse

class LimitedTimeFraViewModel(application: Application) : GLBaseViewModel(application) {
    val type = ObservableField<Int>(0)

    val tag = ObservableField(true)

    var pageNo = 0
    val uc = UiChangeEvent()

    class UiChangeEvent {
        val refreshEvent = SingleLiveEvent<Int>()
        val refreshDataEvent = SingleLiveEvent<List<PreferentPageBean>>()
    }

    val leftTagCommand = BindingCommand<Any>(BindingAction {
        tag.set(true)
    })

    val rightTagCommand = BindingCommand<Any>(BindingAction {
        tag.set(false)
    })

    fun refresh() {
        pageNo = 1
        getPreferentPage()
    }

    fun load() {
        pageNo++
        getPreferentPage()
    }

    fun getPreferentPage() {
        UserServiceFactory.getPreferentPage(
            mapOf(
                "pageNo" to pageNo,
                "pageSize" to 10,
                "sort" to if (tag.get() == true) {
                    "0"
                } else {
                    "1"
                },
                "projectType" to type.get()
            )
        ).subscribe(object :
            AbstractViewModelSubscriber<BaseResponse<PageListBean<PreferentPageBean>>>(this) {
            override fun onNext(t: BaseResponse<PageListBean<PreferentPageBean>>) {
                uc.refreshDataEvent.postValue(t.data.list)
                uc.refreshEvent.postValue(
                    if (t.data.total.toInt() < pageNo * 10) {
                        0
                    } else {
                        1
                    }
                )
            }

            override fun onError(e: Throwable) {
                super.onError(e)
                uc.refreshEvent.postValue(
                    0
                )
            }

        })
    }

}